import {
  useEffect,
  useState,
  useMemo,
  useRef,
  useCallback,
} from 'react';
import cn from 'classnames';
import { Button, message, Tabs } from 'antd';
import MoreConditions from './moreConditions'; // 更多条件弹窗
import MySearchTag, { ISearchTagRef } from './mySearchTag'; // 我的搜索标签组件（文件、文件夹高级搜索打的标签）
import { InbizIcon } from '@inbiz/utils';
import FileFormItem from './FileFormItem'
import {
  ConditionItemType,
  defaultFileShowSchemaOptions,
  defaultFolderShowSchemaOptions,
} from '../../../../designer/conditionsSchema';
import { useSearchUIState } from '../../../../store/hooks/useSearchUIState';
import { useJumpResult } from '../../../../store/hooks/useJumpResult';
import { TextWidget, getMessage } from '@inbiz/react';
import { useSearchUIDispatch } from '../../../../store/hooks/useSearchUIDispatch';
import { useSearchResultPage } from '../../../../store/hooks/useSearchResultPage';
import type { SelectLabelType, IFileFormItemRef } from './FileFormItem'

type IAdvancedDetail = {
  layout: 'inside' | 'outside';
  onClose?: () => void;
};

const { TabPane } = Tabs;

function AdvancedDetail(props: IAdvancedDetail) {
  const { layout = 'outside' } = props;
  const [activeKey, $activeKey] = useState();
  const [moreVisible, $moreVisible] = useState(false);
  const { selectShowTab } = useSearchUIState();
  const updateUIState = useSearchUIDispatch();
  const searchResultPage = useSearchResultPage();
  const [searchEngineData, $searchEngineData] = useState({})
  const [selectLabel, setSelectLabel] = useState<SelectLabelType>(() => {
    if (selectShowTab?.isDMS || selectShowTab?.isFile) {
      return { type: 'local', data: [...defaultFileShowSchemaOptions] };
    } else if (selectShowTab?.isFolder) {
      return { type: 'local', data: [...defaultFolderShowSchemaOptions] };
    } else {
      return { type: 'remote', data: {} };
    }
  });

  // const initmetadataitems = () => {
  //   let initmetaitems = localStorage.getItem(controlId) || sessionStorage.getItem(controlId)
  //   localStorage.removeItem(controlId)
  //   if (searchResultPage.searchResultPage && searchResultPage.searchResultPageType === '_blank') {
  //     // 当是打开新页面时
  //     const resultPages = searchResultPage.searchResultPage.split(',')
  //     const resultPagesId = resultPages[0];
  //     // initmetaitems = localStorage.getItem(resultPagesId + 'metaData') || sessionStorage.getItem(resultPagesId + 'metaData') || '[]'
  //     // localStorage.removeItem(resultPagesId + 'metaData')
  //     // if (initmetaitems) {
  //     //   sessionStorage.setItem(resultPagesId + 'metaData', initmetaitems)
  //     // }
  //   } else {
  //     // 当前页或者绑定组件时
  //     if (initmetaitems) {
  //       sessionStorage.setItem(controlId, initmetaitems)
  //     }
  //   }
  //   if (initmetaitems) {
  //     // 要筛选默认的, 
  //     const parsedItems = JSON.parse(initmetaitems)
  //     const metaArray = selectShowTab!.isFile ? parsedItems.file : parsedItems.folder
  //     setSelectLabel({ type: 'local', data: metaArray })
  //   }
  // }

  // useEffect(() => {
  //   if (selectShowTab!.isFile || selectShowTab!.isFolder) {
  //     initmetadataitems()
  //   }
  // }, [])

  useEffect(() => {
    let metaArray = []
    let initmetaitems = localStorage.getItem('_searchEngineStatus') || sessionStorage.getItem('_searchEngineStatus')
    localStorage.removeItem('_searchEngineStatus')
    if (initmetaitems) {
      sessionStorage.setItem('_searchEngineStatus', initmetaitems)
      // 要筛选默认的, 
      const parsedItems = JSON.parse(initmetaitems)
      
      $searchEngineData(parsedItems)
      metaArray = selectShowTab!.isFile ? parsedItems.metaData?.file : parsedItems.metaData?.folder
    }
    if (selectShowTab?.isFile) {
      if (metaArray?.length > 0) {
        setSelectLabel({ type: 'local', data: metaArray })
      } else {
        setSelectLabel({ type: 'local', data: defaultFileShowSchemaOptions })
      }
    } else if (selectShowTab?.isFolder) {
      if (metaArray?.length > 0) {
        setSelectLabel({ type: 'local', data: metaArray })
      } else {
        setSelectLabel({ type: 'local', data: defaultFolderShowSchemaOptions })
      }
    }
  }, [selectShowTab])
  // 更多条件点击事件
  const onMoreClick = () => {
    $moreVisible(true);
  };

  // 更多条件保存按钮事件
  const onMoreSave = () => {
    $moreVisible(false);
  };
  // 更多条件取消事件
  const onMoreCancel = () => {
    $moreVisible(false);
  };

  const onRemoveHandle = useCallback((field) => {
    setSelectLabel((prev) => {
      if (!prev) return prev;
      return {
        ...prev,
        data: (prev?.data as ConditionItemType[])?.filter?.((item) => item.key !== field.key),
      };
    });
  }, []);

  const onItemPress = useCallback(
    (labelID, data) => {
      setSelectLabel({ ...data, labelID });
    },
    [selectShowTab?.isDMS, selectShowTab?.isFile, selectShowTab?.isFolder],
  );

  const onChangeCondition = useCallback((keys) => {
    setSelectLabel({
      type: 'local',
      data: keys,
    });
  }, []);

  // 更多条件弹窗的参数
  const MoreConditionProps = {
    visible: moreVisible,
    onSave: onMoreSave, // 保存按钮事件
    onCancel: onMoreCancel, // 取消事件
    onChange: onChangeCondition,
    value: selectLabel?.data as ConditionItemType[],
    type: activeKey ? activeKey : selectShowTab?.isFile ? 1 : 2,
  };

  // 更多条件弹窗, 只要是文件和文件夹时才显示
  const MoreConditionsComponent = useMemo(() => {
    return moreVisible ? <MoreConditions {...MoreConditionProps} /> : null;
  }, [moreVisible, onChangeCondition, selectShowTab, activeKey]);

  const onTabChange = (key: string) => {
    $activeKey(key);
    if (key == '1') {
      setSelectLabel({ type: 'local', data: [...defaultFileShowSchemaOptions] });
    } else {
      setSelectLabel({ type: 'local', data: [...defaultFolderShowSchemaOptions] });
    }
  };

  const fileRef = useRef<IFileFormItemRef>(null);
  const folderRef = useRef<IFileFormItemRef>(null);
  const pageRef = useRef<IFileFormItemRef>(null);
  const handleReset = useCallback(() => {
    if (selectShowTab?.isDMS || selectShowTab?.isFile || selectShowTab?.isFolder) {
      if (activeKey == '1' || selectShowTab?.isFile) {
        setSelectLabel({ type: 'local', data: [...defaultFileShowSchemaOptions] });
      } else if(selectShowTab?.isFolder){
        setSelectLabel({ type: 'local', data: [...defaultFolderShowSchemaOptions] });
      }
    } else {
      pageRef.current?.reset();
    }
  }, [selectShowTab, activeKey]);

  const searchTagRef = useRef<ISearchTagRef>(null);
  const handleSaveLabel = useCallback(async () => {
    try {
      let res = selectShowTab?.isDMS
        ? activeKey == '1'
          ? await fileRef.current?.save()
          : await folderRef.current?.save()
        : await pageRef.current?.save();
      if (selectShowTab?.isFile) {
        res = await fileRef.current?.save()
      } else if (selectShowTab?.isFolder) {
        res = await folderRef.current?.save()
      }
      searchTagRef.current?.save(JSON.stringify(res));
    } catch (e) {
      message.error((e as { msg: string })?.msg);
    }
  }, [activeKey, selectShowTab]);
  const setKeyword = useCallback(() => {
    updateUIState({
      keyword: '',
      keywords: [],
    });
  }, [updateUIState]);
  const onJumpResult = useJumpResult(setKeyword);
  const handleSearch = useCallback(async () => {
    const data = {
      data: {
        SearchWhere: ''
      }
    } as {
      data: {
        SearchWhere: string;
        rawSearchWhere: object;
      };
      dmsType?: 'file' | 'folder';
      metaData: any,
      parentFolderLevel?: number,
      parentFolderPath?: string,
      parentTopFolderId?: string,
      parentFolderid: string,
    };
    if (selectShowTab?.isDMS || selectShowTab?.isFolder || selectShowTab?.isFile) {
      let refData: any = {}
      if (activeKey) {
        refData = activeKey == '1' ? await fileRef.current?.search() : await folderRef.current?.search();
        data.dmsType = activeKey == '1' ? 'file' : 'folder';
      } else {
        refData = selectShowTab?.isFile ? await fileRef.current?.search() : await folderRef.current?.search();
        data.dmsType = selectShowTab?.isFile ? 'file' : 'folder';
      }
      const { parentFolderLevel, parentFolderPath, parentTopFolderId, parentFolderid } = refData || {}
      data.parentFolderLevel = parentFolderLevel
      data.parentFolderPath = parentFolderPath
      data.parentTopFolderId = parentTopFolderId
      data.parentFolderid = parentFolderid
      data.metaData = {
        [data.dmsType]: refData?.rawSearchWhere
      }
      data.data.SearchWhere = refData.SearchWhere
    } else {
      data.data = await pageRef.current?.search();
    }
    onJumpResult(data);
  }, [activeKey, selectShowTab]);

  const advancedComponent = useMemo(() => {
    if (selectShowTab?.isDMS) {
      return <div className="advance-form-tabs">
        {/* 更多条件弹窗  */}
        {MoreConditionsComponent}

        <Tabs
          tabPosition={selectShowTab.advancedSearchStyle == 'style1' ? 'top' : 'left'}
          centered={layout === 'inside'}
          activeKey={`${activeKey}`}
          onChange={onTabChange}
          tabBarExtraContent={
            selectShowTab.advancedSearchStyle == 'style1'
              ? {
                right: (
                  <div className="more-conditions" onClick={onMoreClick}>
                    <p>
                      <InbizIcon type="icon-ic-add" />
                      <TextWidget>SearchEngine.moreConditions</TextWidget>
                    </p>
                  </div>
                ),
              }
              : undefined
          }
        >
          <TabPane tab={getMessage('SearchEngine.file')} key="1">
            {selectShowTab.advancedSearchStyle == 'style2' && (
              <div className="more-conditions">
                <p onClick={onMoreClick}>
                  <InbizIcon type="icon-ic-add" />
                  <TextWidget>SearchEngine.moreConditions</TextWidget>
                </p>
              </div>
            )}
            <FileFormItem
              ref={fileRef}
              value={selectLabel}
              isDMS
              advancedSearchStyle={selectShowTab.advancedSearchStyle}
              onRemoveHandle={onRemoveHandle}
              type="file"
              searchEngineData={searchEngineData}
            />
          </TabPane>
          <TabPane tab={getMessage('SearchEngine.folder')} key="2">
            {selectShowTab.advancedSearchStyle == 'style2' && (
              <div className="more-conditions">
                <p onClick={onMoreClick}>
                  <InbizIcon type="icon-ic-add" />
                  <TextWidget>SearchEngine.moreConditions</TextWidget>
                </p>
              </div>
            )}
            <FileFormItem
              ref={folderRef}
              value={selectLabel}
              isDMS
              advancedSearchStyle={selectShowTab.advancedSearchStyle}
              onRemoveHandle={onRemoveHandle}
              type="folder"
              searchEngineData={searchEngineData}
            />
          </TabPane>
        </Tabs>
      </div>
    } else if (selectShowTab?.isFile || selectShowTab?.isFolder) {
      return <div className="advance-form-tabs">
        {/* 更多条件弹窗  */}
        {MoreConditionsComponent}
        <div className="more-conditions">
          <p onClick={onMoreClick}>
            <InbizIcon type="icon-ic-add" />
            <TextWidget>SearchEngine.moreConditions</TextWidget>
          </p>
        </div>
        <FileFormItem
          ref={selectShowTab?.isFile?fileRef : folderRef}
          value={selectLabel}
          isDMS
          advancedSearchStyle={selectShowTab.advancedSearchStyle}
          onRemoveHandle={onRemoveHandle}
          type="file"
          searchEngineData={searchEngineData}
          isFile={selectShowTab?.isFile}
          isFolder={selectShowTab?.isFolder}
        />
      </div>
    } else {
      return <FileFormItem
        ref={pageRef}
        value={selectLabel}
        searchEngineData={searchEngineData}
        advancedSearchStyle={selectShowTab?.advancedSearchStyle}
      />
    }
  }, [selectShowTab, moreVisible, layout, selectLabel])


  return (
    <div className="advanced-detail">
      <div className={cn(`advanced-search-body`)}>
        <div className={`advance-form`}>
          {advancedComponent}
        </div>
        <div
          className={cn('my-tag-body', {
            inside: layout === 'inside',
          })}
        >
          <MySearchTag
            ref={searchTagRef}
            edit={true}
            tagType={activeKey}
            onItemPress={onItemPress}
            ModuleName={selectShowTab?.guid! + (selectShowTab?.isDMS ? '_' + activeKey : '')}
            layout={layout === 'inside' ? 'horizontal' : 'vertical'}
          />
        </div>
      </div>
      <div className="advanced-bottom-btns">
        <div className={'schema-form-button left'}>
          <Button onClick={handleReset}>
            <TextWidget>SearchEngine.reset</TextWidget>{' '}
          </Button>
          <Button onClick={handleSaveLabel}>
            <TextWidget>SearchEngine.saveLabel</TextWidget>
          </Button>
          <Button type="primary" onClick={handleSearch}>
            <TextWidget>SearchEngine.search</TextWidget>
          </Button>
        </div>
        <div className="advanced-drawer-back">
          {props.onClose && (
            <Button type="link" onClick={props.onClose}>
              <TextWidget>SearchEngine.returnToSearch</TextWidget>
            </Button>
          )}
        </div>
      </div>
    </div>
  );
}

export default AdvancedDetail;
